<template>
  <div>
    <Search
      @handleSearch="getList"
      @handleAdd="addDialog = true"
      :btnLoading="btnLoading"
      :queryParams="queryParams"
    ></Search>
    <List
      :list="list"
      :queryParams="queryParams"
      @handleDetail="handleClickDetail"
    ></List>
    <!-- 新建申请 -->
    <el-dialog
      title="请假申请"
      :visible.sync="addDialog"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleCloseDialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="form.leaveType">
            <el-option label="年休假" :value="1"></el-option>
            <el-option label="事假" :value="2"></el-option>
            <el-option label="婚假" :value="3"></el-option>
            <el-option label="丧假" :value="4"></el-option>
            <el-option label="产假" :value="5"></el-option>
            <el-option label="其他" :value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="leaveBeginTime">
          <el-date-picker
            v-model="form.leaveBeginTime"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss "
            type="datetime"
            default-time="08:00:00"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="leaveEndTime">
          <el-date-picker
            v-model="form.leaveEndTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期"
            default-time="18:00:00"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假天数" prop="leaveDate">
          <el-input
            placeholder="根据请假时间自动计算"
            readonly
            style="width: 220px"
            v-model="form.leaveDate"
          ></el-input>
        </el-form-item>
        <el-form-item label="请假原因" prop="leaveReason">
          <el-input
            type="textarea"
            rows="2"
            v-model="form.leaveReason"
            placeholder="请输入请假原因"
          />
        </el-form-item>
        <!-- :on-success="handleFileSuccess" -->
        <el-form-item label="附件上传" prop="reason">
          <el-upload
            class="upload-demo"
            accept=".txt,.pdf,.doc,.docx,.xls,.xlsx"
            drag
            multiple
            :action="upload.newUrl"
            :headers="upload.headers"
            ref="upload"
            :auto-upload="true"
            :file-list="fileList"
            :on-change="changeFile"
            :on-remove="removeFile"
            name="uploadFile"
            :data="{
              processDefinitionKey: 'flowLeave',
              datasourceId: '1440945228130291712',
              fieldName: 'leave_file',
              asImage: false,
            }"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <!-- :on-success="picturHhandleFileSuccess" -->
        <el-form-item label="图片上传" prop="reason1">
          <el-upload
            class="upload-demo"
            accept=".jpg,.gif,.png,.jpeg"
            drag
            multiple
            list-type="picture"
            :action="upload.newUrl"
            :headers="upload.headers"
            ref="pictureUpload"
            :auto-upload="true"
            :file-list="pictureFileList"
            :on-change="pictureChangeFile"
            :on-remove="picturRremoveFile"
            name="uploadFile"
            :data="{
              processDefinitionKey: 'flowLeave',
              datasourceId: '1440945228130291712',
              fieldName: 'picture',
              asImage: true,
            }"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将图片拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-row type="flex" justify="end" style="margin-top: 10px">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>
  </div>
</template>
<script>
import uploadMixin from './uploadMixins.js';
import Search from './modules/Search.vue';
import List from './modules/LeaveList.vue';
import getTotal from '@/utils/leaveLength';
import { Leave } from '@/api/approve.js';
import { getToken } from '@/utils';
import requestUrl from '@/core/http/requestUrl';
// const processDefinitionKey = 'flowLeave';
// const processDefinitionName = '请假申请'

export default {
  mixins: [uploadMixin],
  data () {
    return {
      createTime: [],
      flowStatus: undefined,
      btnLoading: false,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      form: {
        leaveType: 1,
        leaveBeginTime: null,
        leaveEndTime: null,
        leaveReason: '',
        leaveDate: 0
      },
      addDialog: false,
      watchDialog: false,
      rules: {
        leaveBeginTime: [
          {
            required: true,
            message: '请选择时间'
          }
        ],
        leaveEndTime: [
          {
            required: true,
            message: '请选择时间'
          }
        ],
        leaveReason: [
          {
            required: true,
            message: '请输入原因'
          }
        ]
      },
      pickerOptions: {
        selectableRange: ['08:00:00 - 18:00:00']
      },
      fileList: [],
      pictureFileList: [], // 图片文件列表
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: requestUrl('admin/app/leave/upload'),
        // 通用上传的地址
        newUrl: requestUrl('admin/flow/flowOnlineOperation/upload')
      },
      row: {}
    };
  },
  components: {
    Search,
    List
  },
  watch: {
    duration (val) {
      this.form.leaveDate = val;
    },
    $route () {
      this.getList()
    }
  },
  computed: {
    duration () {
      // let str = getTotal('2022-10-14 8:00:00', '2022-10-14 14:00:00', 8, 18, true, 12, 14)
      if (this.form.leaveBeginTime && this.form.leaveEndTime) {
        let obj = getTotal(
          this.form.leaveBeginTime,
          this.form.leaveEndTime,
          8,
          18,
          true,
          12,
          14
        );
        let { days, hours } = obj;
        if (hours <= 4 && hours > 0) {
          days += 0.5;
        }
        if (hours > 4) {
          days += 1;
        }
        return days;
      } else {
        return 0;
      }
    }
  },
  created () {
    this.getList();
  },
  methods: {
    handleSearch () { },
    // 新建
    handleAdd () {
      this.addDialog = true;
    },
    // 列表
    getList () {
      Leave.list(this, {
        pageParam: {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        },
        flowWorkOrderDtoFilter: {
          flowStatus: this.queryParams.flowStatus,
          createTimeStart: this.queryParams.time && this.queryParams.time[0],
          createTimeEnd: this.queryParams.time && this.queryParams.time[1]
        },
        orderParam: [
          {
            fieldName: 'createTime',
            asc: false
          }
        ]
      }).then((res) => {
        this.list = res.data.dataList;
        this.total = res.data.totalCount;
      });
    },
    // 新建-提交
    submitForm () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let arr = []
          this.fileList.forEach(item => {
            arr.push(item.response.data)
          });
          let arr1 = [];
          this.pictureFileList.forEach(item => {
            arr1.push(item.response.data)
          });
          Leave.add(this, {
            leaveDto: {
              ...this.form,
              leaveFile: JSON.stringify(arr),
              picture: JSON.stringify(arr1)
            },

            flowTaskCommentDto: { approvalType: 'agree' },
            taskVariableData: { ...this.getUserInfo }
          }).then(res => {
            this.addDialog = false
            this.$message.success('启动成功')
            this.getList()
          })
        }
      });
    },
    handleClickDetail (row) {
      console.log(row)
      this.row = row
      this.watchDialog = true
    },
    handleCloseDialog () {
      this.$refs.form.resetFields()
      this.fileList = []
    }
  }
};
</script>
<style lang="scss">
.leave-watch-dialog {
  .el-form-item__label {
    font-size: 16px;
    font-weight: bold;
  }
}
</style>
